package DataAccess;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import Domain.Account;
import Domain.Product;
import Domain.ShoppingCart;
import Exception.DadosException;

public class DAOShoppingCart extends DAOGenerico<ShoppingCart> implements
		IDAOShoppingCart {

	public DAOShoppingCart() {
		super();
		// TODO Auto-generated constructor stub
	}

	public List<ShoppingCart> consultarTodos() {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("Accenture");
		EntityManager entityManager = emf.createEntityManager();

		TypedQuery<ShoppingCart> tq = entityManager.createQuery(
				"SELECT aa FROM ShoppingCart aa", ShoppingCart.class);

		List<ShoppingCart> list = tq.getResultList();
		entityManager.close();
		emf.close();
		return list;

	}

	public ShoppingCart findByAccount(Account ac) {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("Accenture");
		EntityManager entityManager = emf.createEntityManager();

		TypedQuery<ShoppingCart> tq = entityManager.createQuery(
				"SELECT s FROM ShoppingCart s WHERE s.account=:usuario",
				ShoppingCart.class);
		tq.setParameter("usuario", ac);

		List<ShoppingCart> list = tq.getResultList();

		entityManager.close();
		emf.close();

		if (list.size() > 0) {
			return list.get(0);
		}

		return null;
	}

	public ShoppingCart consultarPorIdNOVO(Integer id) {

		EntityManagerFactory emf = Persistence
				.createEntityManagerFactory("Accenture");
		EntityManager entityManager = emf.createEntityManager();

		ShoppingCart c = entityManager.find(ShoppingCart.class, id);

		entityManager.close();
		emf.close();
		return c;
	}
	
	 public final void remover(ShoppingCart objeto) throws DadosException {

			EntityManagerFactory emf = Persistence.createEntityManagerFactory("Accenture");
			entityManager = emf.createEntityManager();

			EntityTransaction tx = entityManager.getTransaction();
			try {
				tx.begin();

				Query query = entityManager
						.createQuery("DELETE FROM ShoppingCart c WHERE c= :p");
				int deletedCount = query.setParameter("p", objeto).executeUpdate();

				tx.commit();
			} catch (Exception e) {
				e.printStackTrace();
				if (tx != null && tx.isActive()) {
					tx.rollback();
				}
				throw new DadosException(DadosException.ERROR_DEL, e);
			}

			entityManager.close();
			emf.close();
		}

}
